#include "image.h"

#include <string.h>

#include <IL/il.h>
#include <IL/ilu.h>

namespace venus {
bool Image::Load(const char *filename) {
  if (0 != width_ || 0 != height_) { 
    this->Release();
  }
  ilInit();
  ilOriginFunc(IL_ORIGIN_UPPER_LEFT);
  ilEnable(IL_ORIGIN_SET);

  ILuint image_id = ilGenImage();
  ilBindImage(image_id);
  if (!ilLoadImage(filename)) {
    Error("'Image::Load', failed to load file \"%s\"", filename);
    return false;
  }
  width_ = ilGetInteger(IL_IMAGE_WIDTH);
  height_ = ilGetInteger(IL_IMAGE_HEIGHT);
  format_ = ilGetInteger(IL_IMAGE_FORMAT);
  type_ = ilGetInteger(IL_IMAGE_TYPE);
  int bpp = ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL);
  int image_size = width_ * height_ * bpp;
  data_ = new char[image_size];
  //it seems that devil load the image upside-down, a flip is needed!
  iluFlipImage();
  memcpy(data_, ilGetData(), image_size);
  ilDeleteImage(image_id);
  
  return true;
}

} // namespace venus
